package com.wbs.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wbs.resutil.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
 * @Author: 芝梦
 * @Description: 上传
 * @DateTime: 2024/1/30 21:58
 */
@RequestMapping("file")
@RestController
public class FileController {

    @PostMapping("upload")
    public Result upload(@RequestBody MultipartFile img){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String start = "https://";
        String end = "oss-cn-beijing.aliyuncs.com";
        String endpoint = start + end ;
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        String accessKey = "LTAI5tK3EPkwdL2xagiytgkW";
        String secret = "wAQBScIoFOPHNN3aRMU44FnEM9IYW8";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "dongdongshop-zhimeng";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        //获取前端上传的文件名
        String filename = img.getOriginalFilename();
        //yyyy/MM/dd/uuid.ing
        String objectName = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secret);

        try {
            //获取图片流信息
            InputStream inputStream = img.getInputStream();
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String url = start + bucketName + "." + end + "/" +objectName;
        return Result.SUCCESS().setData(url);
    }
}
